/*
 * Project Name: jmax
 * File Name: JsonRedisSerializer.java
 * Copyright: Copyright(C) 1985-2016 ZKTeco Inc. All rights reserved.
 */
package com.xdtech.jmax.test;

import java.nio.charset.Charset;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.Assert;

import com.google.gson.Gson;
import com.xdtech.sys.model.User;

/**
 * TODO 一句话功能简述，请确保和下面的block tags之间保留一行空行
 * <p>
 * TODO 功能详细描述，若不需要请连同上面的p标签一起删除
 * 
 * @author <a href="max.zheng@zkteco.com">郑志雄</>
 * @version TODO 添加版本
 * @see 相关类或方法，不需要请删除此行
 * @since 2016-2-3 上午10:15:58
 */
public class JsonRedisSerializer implements RedisSerializer<Object> {

	private final Charset charset;

	public JsonRedisSerializer() {
		this(Charset.forName("UTF8"));
	}
	public JsonRedisSerializer(Charset charset) {
		Assert.notNull(charset);
		this.charset = charset;
	}

	/* (非 Javadoc)
	 * serialize
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param t
	 * @return
	 * @throws SerializationException
	 * @see org.springframework.data.redis.serializer.RedisSerializer#serialize(java.lang.Object)
	 */
	@Override
	public byte[] serialize(Object t) throws SerializationException
	{
		String value = new Gson().toJson(t);
		return (value == null ? null : value.getBytes(charset));
	}

	/* (非 Javadoc)
	 * deserialize
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param bytes
	 * @return
	 * @throws SerializationException
	 * @see org.springframework.data.redis.serializer.RedisSerializer#deserialize(byte[])
	 */
	@Override
	public User deserialize(byte[] bytes) throws SerializationException
	{
		String value = (bytes == null ? null : new String(bytes, charset));
		if (null != value)
		{
			return new Gson().fromJson(value, User.class);
		}
		return null;
	}
}
